package com.dingwen.sprboojwtstu.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.dingwen.sprboojwtstu.exception.ServiceException;
import com.dingwen.sprboojwtstu.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * JWT 令牌 校验 拦截器
 *
 * @author dingwen
 * 2021.05.31 13:45
 */
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 前置处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            Optional.ofNullable(token).orElseThrow(() -> new ServiceException("token不能为空"));
            JwtUtil.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            throw new ServiceException("token已过期");
        } catch (SignatureVerificationException e) {
            throw new ServiceException("签名错误");
        } catch (AlgorithmMismatchException e) {
            throw new ServiceException("加密算法不匹配");
        } catch (ServiceException e) {
            throw new ServiceException("token不能为空");
        } catch (Exception e) {
            throw new ServiceException("无效token");
        }

    }
}
